package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.ImageServerUtil.EnumImageServer;
import com.situ.mall.util.QiniuUtil;

@Controller
@RequestMapping("/upload")
public class UploadController {

	@RequestMapping("/uploadImg")
	@ResponseBody
	public ServerResponse uploadImg(MultipartFile file) {
		String fileName = "";
		if (ImageServerUtil.IMG_SERVER == EnumImageServer.QINIU) {
			try {
				fileName = QiniuUtil.uploadImage(file.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {// 上传到本地
			fileName = uploadToLocal(file);
		}
		
		// fileName文件的名字是要存储到数据库里面，所以要告诉前台，插入到前台的form表单里面
		// 执行insert的时候product对象的属性mainImage才有值
		return ServerResponse.createSuccess("上传成功", fileName);
	}


	private String uploadToLocal(MultipartFile file) {
		// 为了防止文件重名（重名的文件会被覆盖丢失），所以要生成一个不重复的随机的名字
		// d50bc74b8fbe41bcb83207ea7291a17a
		String name = UUID.randomUUID().toString().replace("-", "");
		// .jpg   .png
		System.out.println(file.getOriginalFilename());// a.png
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		// d50bc74b8fbe41bcb83207ea7291a17a.png
		String fileName = name + "." + extension;
		// d:/pic/d50bc74b8fbe41bcb83207ea7291a17a.png
		String filePath = "D:\\pic\\" + fileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	
	public static void main(String[] args) {
		String name = UUID.randomUUID().toString().replace("-", "");
		System.out.println(name);// d50bc74b8fbe41bcb83207ea7291a17a
	}
	
	
	
}
